<?php
require_once 'database21.php';

class Classes extends Database {
    public function createClass($name, $department_id) {
        try {
            $stmt = $this->conn->prepare("INSERT INTO classes (class_name, department_id) VALUES (:name, :department_id)");
            $stmt->execute([
                ':name' => $name,
                ':department_id' => $department_id
            ]);
            return $this->conn->lastInsertId();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        }
    }

    public function getClasses() {
        try {
            $stmt = $this->conn->prepare("
                SELECT c.*, d.department_name 
                FROM classes c 
                LEFT JOIN departments d ON c.department_id = d.department_id
            ");
            $stmt->execute();
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        }
    }

    public function getClass($id) {
        try {
            $stmt = $this->conn->prepare("
                SELECT c.*, d.department_name 
                FROM classes c 
                LEFT JOIN departments d ON c.department_id = d.department_id 
                WHERE c.class_id = :id
            ");
            $stmt->execute([':id' => $id]);
            return $stmt->fetch();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        }
    }

    public function updateClass($id, $name, $department_id) {
        try {
            $stmt = $this->conn->prepare("UPDATE classes SET class_name = :name, department_id = :department_id WHERE class_id = :id");
            $stmt->execute([
                ':id' => $id,
                ':name' => $name,
                ':department_id' => $department_id
            ]);
            return $stmt->rowCount();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        }
    }

    public function deleteClass($id) {
        try {
            // 检查是否有学生属于该班级
            $stmt = $this->conn->prepare("SELECT * FROM students WHERE class_id = :id");
            $stmt->execute([':id' => $id]);

            if ($stmt->rowCount() > 0) {
                throw new Exception("无法删除, 该班级下有学生存在");
            }

            $stmt = $this->conn->prepare("DELETE FROM classes WHERE class_id = :id");
            $stmt->execute([':id' => $id]);
            return $stmt->rowCount();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        } catch (Exception $e) {
            die("错误: " . $e->getMessage());
        }
    }

    // 获取所有系部信息，用于班级管理中的系部选择
    public function getDepartments() {
        try {
            $stmt = $this->conn->prepare("SELECT * FROM departments");
            $stmt->execute();
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            die("错误: " . $e->getMessage());
        }
    }
}
?>